package com.zhaojun.cloud.service.sso.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.zhaojun.cloud.common.mapper.service.IUserAccessService;
import com.zhaojun.cloud.common.pojo.User;
import com.zhaojun.cloud.common.result.CommonResult;
import com.zhaojun.cloud.service.api.RedisService;
import com.zhaojun.cloud.service.api.UserService;
import com.zhaojun.cloud.support.shiro.ShiroKit;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.misc.Cache;

import java.util.HashMap;
import java.util.Map;

/**
 * wwj
 * 2018/11/30  16:10
 */
@RestController
public class SSOController {

    private Logger logger = LoggerFactory.getLogger(SSOController.class);

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserService userService;

    @Autowired
    private IUserAccessService userAccessService;

    @RequestMapping("/login")
    public CommonResult login(@RequestParam String username, @RequestParam String password) {
        Subject currentUser = SecurityUtils.getSubject();
        Map jsonObject = new HashMap<>();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password.toCharArray());
        try {
            currentUser.login(token);
            jsonObject.put("token", currentUser.getSession().getId());
            jsonObject.put("id", ((User)currentUser.getPrincipal()).getId());
            jsonObject.put("msg", "登录成功");
            logger.info(JSONUtils.toJSONString(jsonObject));
            return CommonResult.success(jsonObject);
        } catch (IncorrectCredentialsException e) {
            jsonObject.put("msg", "密码错误");
            logger.error(e.getMessage(), e);
            return CommonResult.success(jsonObject);
        } catch (LockedAccountException e) {
            jsonObject.put("msg", "登录失败，该用户已被冻结");
            logger.error(e.getMessage(), e);
            return CommonResult.success(jsonObject);
        } catch (AuthenticationException e) {
            jsonObject.put("msg", "该用户不存在");
            logger.error(e.getMessage(), e);
            return CommonResult.success(jsonObject);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return CommonResult.success(jsonObject);
        }
    }

    /**
     * 简易的注册
     */
    @PostMapping("/register")
    public CommonResult register(@RequestParam String username, @RequestParam String password) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(ShiroKit.md5(password, username));
        userAccessService.save(user);
        return CommonResult.success();
    }

    @RequestMapping("/test")
    public CommonResult test() {
        Map<Integer, Object> reulst = new HashMap<>();
        reulst.put(1, userService.findUserById(1l));
        return CommonResult.success(reulst);
    }

    @RequestMapping("/logout")
    public Object logout() {
        SecurityUtils.getSubject().logout();
        return CommonResult.build(200, "退出成功");
    }

    @RequestMapping(value = "/notLogin", method = RequestMethod.GET)
    public Object notLogin() {
        return CommonResult.build(200, "您尚未登录");
    }

    @RequestMapping(value = "/notRole", method = RequestMethod.GET)
    public Object notRole() {
        return CommonResult.build(200, "您没有权限");
    }
}
